package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzService clazzService;


    @Override
    public void violation(Integer id, Integer score) {
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id)
                .setSql("violation_score = violation_score + score ", score)
                .setSql("violation_count = violation_count + 1");
        update(updateWrapper);
    }

    @Override
    public PageResult<Student> getStudent(StudentQueryParam student) {
        Page<Student> page = new Page<>(student.getPage(),student.getPageSize());
         page = lambdaQuery().like(Student::getName,student.getName())
                .eq(Student::getDegree,student.getDegree())
                 
               .page(page);

        List<Student> students = page.getRecords();
        List<Integer> clazzIds = students.stream().map(stu -> stu.getClazzId()).collect(Collectors.toList());
      if(!clazzIds.isEmpty()){
          List<Clazz> clazzes = clazzService.listByIds(clazzIds);
          students.forEach(stu ->{
              clazzes.forEach(clazz ->{
                  if(clazz != null && stu.getClazzId().equals(clazz.getId())){
                      stu.setClazzName(clazz.getName());
                  }
              });
          });
      }

        return new PageResult<>(page.getTotal(), students);
    }
}
